﻿using CIS.Server.EFCore;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace CIS.Server.Repository
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {
        private CISServerContext _context;
        public BaseRepository()
        {
            _context = new CISServerContext();
        }


        #region 添加操作
        public Task<bool> AddAsync(T entity)
        {
            _context?.Set<T>().Add(entity);
            return Task.FromResult(_context?.SaveChanges() > 0);
        }

        public Task<bool> AddManyAsync(List<T> entities)
        {
            _context?.Set<T>().AddRange(entities);
            return Task.FromResult(_context?.SaveChanges() > 0);
        }
        #endregion


        #region 查询操作
        public Task<bool> AnyAsync(Expression<Func<T, bool>> where)
        {
            return Task.FromResult(_context.Set<T>().Where(where).Any());
        }

        public async Task<List<T>> GetAllAsync(bool useCache = false, int cacheSecond = 3600)
        {
            return await _context.Set<T>().ToListAsync<T>();
        }

        public async Task<T> GetByIdAsync(object pkValue)
        {
            return null;
        }

        public Task<int> GetCountAsync(Expression<Func<T, bool>> where)
        {
            throw new NotImplementedException();
        }

        public async Task<T> GetFirst(Expression<Func<T, bool>> where)
        {
            return await _context.Set<T>().FirstOrDefaultAsync(where);
        }

        public Task<T> GetFirst(string parm)
        {
            throw new NotImplementedException();
        }

        public Task<List<T>>? GetManyAsync(Func<T,bool> where)
        {
            return Task.FromResult(_context.Set<T>().Where(where).ToList());
        }

        public TResult Sum<TResult>(Expression<Func<T, bool>> where, Expression<Func<T, TResult>> field)
        {
            throw new NotImplementedException();
        }
        #endregion



    }
}
